<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? t('common.edit') : t('common.create')"
    @register="register"
    @ok="handleSubmit"
    :destroyOnClose="true"
    :minHeight="400"
    :width="500"
  >
    <BasicForm @register="registerForm" />
    <p>{{ t('routes.demo.PartAndDrawingSettings.tip1') }}</p>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getPartAndDrawModalForm } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { addPartDocTypeList, UpdatePartAndDocRelationship } from '/@/api/demo/system';

  const isUpdate = ref<boolean>(false);
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);

  // 提交
  const handleSubmit = async () => {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) await UpdatePartAndDocRelationship(values);
      else await addPartDocTypeList(values);

      closeModal();
      emit('success');
      createMessage.success(t('common.saveSuccess'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue(data.record);
    }
  });

  // 属性详情
  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
    schemas: getPartAndDrawModalForm(),
    showResetButton: false,
    showSubmitButton: false,
  });
</script>
